package cn.rubbit.plug;

import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import cn.rubbit.ApplicationContext;

public class PlugManager {
	public PlugManager() {
	}

	@SuppressWarnings({ "unchecked", "resource" })
	public void load() {
		String filepath = PlugManager.class.getResource("/") + ApplicationContext.PLUG_XML;
		SAXBuilder builder = new SAXBuilder(false);
		try {
			Document document = builder.build(filepath);
			Element root = document.getRootElement();
			List<Element> plugins = root.getChildren("plugin");
			for (int i = 0; i < plugins.size(); i++) {
				Element plug = plugins.get(i);
				String name = plug.getChild("name").getValue();
				String cls = plug.getChild("class").getValue();
				String jarPath = plug.getChild("jar").getValue();
				URL[] url = null;
				String[] jars = jarPath.split(";");
				url = new URL[jars.length];
				for (int n = 0; n < jars.length; n++) {
					url[n] = new URL(PlugManager.class.getResource("/") + "plugin\\" + jars[n]);
					System.out.println(url[n].getFile());
				}
				Class<?> clazz = new URLClassLoader(url, Thread.currentThread().getContextClassLoader()).loadClass(cls);
				Plugin plg = (Plugin) clazz.newInstance();
				if (!plg.isConflict() && plg.isReady()) {
					ApplicationContext.set(name, plg);
				}
			}
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
	}
}
